package com.chmingx.springcloud.service.impl;

import com.chmingx.springcloud.dao.OrderDao;
import com.chmingx.springcloud.domain.Order;
import com.chmingx.springcloud.service.AccountService;
import com.chmingx.springcloud.service.OrderService;
import com.chmingx.springcloud.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private StorageService storageService;

    @Autowired
    private AccountService accountService;

    /**
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     * 简单说：下订单->扣库存->减余额->改状态
     * @param order
     */
    @Override
    @GlobalTransactional(name = "fsp-create-order", rollbackFor = Exception.class) // //rollbackFor = Exception.class表示对任意异常都进行回滚
    public void create(Order order) {
        // 1 新建订单
        orderDao.create(order);

        // 2 扣减库存
        storageService.decrease(order.getProductId(), order.getCount());

        // 3 口径账户
        accountService.decrease(order.getUserId(), order.getMoney());

        // 4 修改订单状态
        orderDao.update(order.getId(), 1);
    }
}
